//
//  ShapeView.swift
//  IOS9DrawShapesTutorial
//
//  Created by 岚海网络 on 2019/4/2.
//  Copyright © 2019年 ljm. All rights reserved.
//

import UIKit
import CoreGraphics

class ShapeView: UIView {

    var currentShapeType:Int = 0
    
    init(frame: CGRect , shape:Int) {
        super.init(frame:frame)
        self.currentShapeType = shape
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func draw(_ rect: CGRect) {
        switch currentShapeType {
        case 0: drawLine()
        case 1: drawRectage()
        case 2: drawCircle()
        default:
            print("default")
        }
    }
    
    
    //drawlines
    func drawLine() {
        
        let ctx = UIGraphicsGetCurrentContext()
        
        ctx?.beginPath()
        ctx?.move(to: CGPoint(x: 20, y: 20))
        ctx?.addLine(to: CGPoint(x: 250, y: 100))
        ctx?.addLine(to: CGPoint(x: 100, y: 200))
        ctx?.setLineWidth(1)
        
        ctx?.closePath()
        ctx?.strokePath()
    }
    
    //drawRectage
    func drawRectage() {
        
        let center = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
        let rectageWith : CGFloat = 100
        let rectageHeight : CGFloat = 50
        
        let ctx = UIGraphicsGetCurrentContext()
        
        ctx?.addRect(CGRect(x: center.x - rectageWith / 2, y: center.y - rectageHeight / 2, width: rectageWith, height: rectageHeight))
        ctx?.setLineWidth(2)
        ctx?.setStrokeColor(UIColor.orange.cgColor)
        ctx?.strokePath()
        
        ctx?.setFillColor(UIColor.green.cgColor)
        ctx?.addRect(CGRect(x: center.x - rectageWith / 2, y: center.y - rectageHeight / 2, width: rectageWith, height: rectageHeight))
        ctx?.fillPath()
        
    }
    
    //drawCircle
    func drawCircle() {
        
        let center = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
        let ctx = UIGraphicsGetCurrentContext()
        
        ctx?.beginPath()
        
        ctx?.setLineWidth(3)
        
        let x:CGFloat = center.x
        let y:CGFloat = center.y
        
        let radius:CGFloat = 90
        let angle:CGFloat = CGFloat(Double(2 * M_PI))
        
        ctx?.addArc(center: CGPoint(x: x, y: y), radius: radius, startAngle: 0, endAngle: angle, clockwise: false)
        
        ctx?.strokePath()
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
